﻿using System;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace CrackNET
{
    /// <summary>
    /// This control appears in the top-left corner of the MainWindow.
    /// It shows a green alien who blinks on demand.
    /// </summary>
    public partial class AlienDudeControl : UserControl
    {
        #region Fields

        const int BLINK_SPEED = 16; // milliseconds

        readonly DispatcherTimer _alienDudeBlinkingTimer = new DispatcherTimer();
        readonly BitmapImage[] _blinkImages = new BitmapImage[]
        {
            new BitmapImage(new Uri("Images/AlienDude0.png", UriKind.Relative)),
            new BitmapImage(new Uri("Images/AlienDude1.png", UriKind.Relative)),
            new BitmapImage(new Uri("Images/AlienDude2.png", UriKind.Relative)),
            new BitmapImage(new Uri("Images/AlienDude3.png", UriKind.Relative)),
            new BitmapImage(new Uri("Images/AlienDude4.png", UriKind.Relative)),
            new BitmapImage(new Uri("Images/AlienDude5.png", UriKind.Relative)),
            new BitmapImage(new Uri("Images/AlienDude6.png", UriKind.Relative)),
            new BitmapImage(new Uri("Images/AlienDude7.png", UriKind.Relative))
        };

        int _blinkIndex;

        #endregion // Fields

        #region Constructor

        public AlienDudeControl()
        {
            InitializeComponent();

            _alienDudeBlinkingTimer.Interval = TimeSpan.FromMilliseconds(BLINK_SPEED);
            _alienDudeBlinkingTimer.Tick += this.OnAlienDudeBlinkingTimerTick;
        }

        #endregion // Constructor

        #region Blink

        public void Blink()
        {
            if (!_alienDudeBlinkingTimer.IsEnabled)
            {
                _blinkIndex = 0;
                _alienDudeBlinkingTimer.Start();
            }
        }

        #endregion // Blink

        #region ObservableBlinkDuration

        public TimeSpan ObservableBlinkDuration
        {
            get { return TimeSpan.FromMilliseconds(_blinkImages.Length * BLINK_SPEED * 5); }
        }

        #endregion // ObservableBlinkDuration

        #region OnAlienDudeBlinkingTimerTick

        void OnAlienDudeBlinkingTimerTick(object sender, EventArgs e)
        {
            if (_blinkIndex == _blinkImages.Length)
            {
                Array.Reverse(_blinkImages);
            }

            this.alienDude.Source = _blinkImages[_blinkIndex % _blinkImages.Length];

            if (++_blinkIndex == (_blinkImages.Length * 2))
            {
                _alienDudeBlinkingTimer.Stop();
                Array.Reverse(_blinkImages);
            }
        }

        #endregion // OnAlienDudeBlinkingTimerTick
    }
}